# -*- coding: utf-8 -*-
import json
import time

from crawler.utils.Singleton import Singleton
from crawler.connection.MySQL import MySQLConnection
from crawler.connection.RabbitMq import RabbitMQConnection, MonitorRabbit
from scheduler.create_task_from_db.setting import QUEUE_NAME, CHOICE_DB, TASKS_INFO_SQL, MIN_QUEUE_COUNT


@Singleton
class CreateTask(RabbitMQConnection):
    def __init__(self):
        self.queue_name = QUEUE_NAME
        self.max_queue_count = MIN_QUEUE_COUNT
        self.tasks_info_sql = TASKS_INFO_SQL
        self.connect = MySQLConnection(dbName=CHOICE_DB)
        self.monitor = MonitorRabbit(self.queue_name)

    def _before_create_task(self):
        self.channel = self.get_channel()
        self.create_queue(self.channel, self.queue_name)
        time.sleep(0.1)
        current_queue_count = int(self.monitor.get_queue_count())
        if current_queue_count < self.max_queue_count:
            self.push_task()

    def query_from_db(self):
        return self.connect.query(self.tasks_info_sql)

    def push_task(self):
        data = self.query_from_db()
        for item in data:
            payload = json.dumps(item)
            self.publish_insert_task(task=payload, routing_key=self.queue_name)

    def run(self):
        self._before_create_task()
        # self.connect.close()
